<?php

namespace mpend\modules\passport\models;

use Yii;
use yii\db\Exception;
use mpend\models\User;
use common\models\user\UserMeta;
use common\helpers\StringHelper;

/**
 * 小程序用户信息登录
 * 
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class MpLoginForm extends \common\models\LoginBaseModel {

    /**
     * @var string 昵称
     */
    public $user_id;

    /**
     * @var string 昵称
     */
    public $nickName;

    /**
     * @var string 性别
     */
    public $gender;

    /**
     * @var string 头像
     */
    public $avatarUrl;

    /**
     * @var string 国家
     */
    public $country;

    /**
     * @var string 省份
     */
    public $province;

    /**
     * @var string 城市
     */
    public $city;

    /**
     * @var string 城市
     */
    public $mobile;

    /**
     * @var \common\models\app\AppToken 客户端Token信息模型
     */
    public $token = null;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id'], 'required'],
            [['user_id', 'gender'], 'integer'],
            [['mobile'], 'string', 'max' => 11],
            [['nickName', 'avatarUrl', 'country', 'province', 'city'], 'string', 'max' => 255],
            [['mobile'], 'validateMobile'],
        ];
    }

    /**
     * 设置用户信息
     * @return User|null
     */
    public function validateMobile($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $mobile = $this->$attribute;
        if ($mobile) {
            $mobileUser = User::findByMobile($this->$attribute);
            if ($mobileUser && $mobileUser->id != $this->user_id) {
                $this->addError($attribute, '当前手机号已被占用');
            }
        }
    }

    /**
     * 设置用户信息
     * @return User|null
     */
    protected function setUser() {
        return User::findOne($this->user_id);
    }

    /**
     * 账号登录
     * @return User
     */
    public function login() {
        if (!$this->validate()) {
            $this->dumpError('登录失败');
        }
        $user = $this->getUser();
        $user->status = User::STATUS_ACTIVE;
        $user->gender = (int) $this->gender;
        if ($this->avatarUrl) {
            $user->avatar = $this->avatarUrl;
        }
        $user->setNickname($this->nickName);
        if ($this->mobile) {
            $user->setMobile($this->mobile);
        }
        //
        $meta = $user->meta;
        if (!$meta) {
            $meta = new UserMeta();
            $meta->id = $user->id;
        }
        $meta->gender = $user->gender;
        $address = array_filter([
            $this->country,
            $this->province,
            $this->city,
        ]);
        $meta->location = implode('·', $address);
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save()) {
                throw new Exception('用户激活失败！');
            }
            if (!$meta->save()) {
                throw new Exception('用户信息保存失败！');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return $user;
    }

}
